package cn.tkb.user.controller;

import cn.tkb.basic.exception.BusinessException;
import cn.tkb.basic.util.AjaxResult;
import cn.tkb.basic.util.PageQuery;
import cn.tkb.user.domain.User;
import cn.tkb.user.dto.UserDto;
import cn.tkb.user.query.UserQuery;
import cn.tkb.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    //新增和修改
    @RequestMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if (user.getId() == null){
                userService.add(user);
            }else {
                userService.update(user);
            }
            return  AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("操作失败！！！");
        }
    }
    //查询用户
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.QeuryById(id);
    }
    //删除用户
    @DeleteMapping("/{id}")
        public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("删除失败");
        }

    }
    //批量删除
    @PatchMapping
    public AjaxResult BatchDelete(@RequestBody List<Long> ids){
        try {
            userService.BatchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.fail(e.getMessage());
        }
    }
    //查询所有用户
    @GetMapping
    public List<User> queryAll(){
        return userService.QeuryAll();
    }
    //高级查询和分页查询
    @PostMapping
    public PageQuery<User> queryPage(@RequestBody UserQuery query){
       return userService.findPage(query) ;
    }
    @PostMapping("/register/phone")
    public AjaxResult RegisterByphone(@RequestBody UserDto userDto){
        try {
            userService.RegisterByphone(userDto);
            return  AjaxResult.success();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("欧吼！！系统开小差了我们正在处理请稍后重试！！！");
        }
    }
}
